package com.common.network;

import android.content.Context;
import android.text.TextUtils;

import com.common.network.help.Error;
import com.common.network.response.BaseResponse;
import com.common.utils.NetworkUtil;
import com.google.gson.JsonParseException;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import retrofit2.HttpException;


/**
 * @author : cms
 * @类名：
 * @e-mail : 254419013@qq.com
 * @time : 2017/3/29 22:02
 * @desc :
 */

public abstract class RetrofitManager {


    private static final String TAG = "RetrofitManager";

    public void errorInfo(Context context, Throwable e, BaseResponse baseResponse) {
        Throwable throwable = e;
        /**
         * 获取根源 异常
         */
        while (throwable.getCause() != null) {
            e = throwable;
            throwable = throwable.getCause();
        }
        if (e instanceof HttpException) {//对网络异常
            HttpException httpException = (HttpException) e;
            if (TextUtils.isEmpty(httpException.getMessage())) {
                baseResponse.setError("error_net_fail");
                EventBus.getDefault().post(baseResponse);
            } else {
                String errorMsg = httpException.getMessage();
                if (TextUtils.isEmpty(errorMsg)) {
                    baseResponse.setError("error_net_fail");
                    EventBus.getDefault().post(baseResponse);
                } else {
                    baseResponse.setError(errorMsg);
                    EventBus.getDefault().post(baseResponse);
                }

            }
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {//解析异常
            baseResponse.setError("error_net_parse");
            EventBus.getDefault().post(baseResponse);
        } else if (e instanceof UnknownHostException) {//未知主机
            //  Log.d(TAG, "1------------ 未知主机");
            baseResponse.setError(Error.ERROR_NETWORK_IS_NOT_AVAILABLE);
            EventBus.getDefault().post(baseResponse);
        } else if (e instanceof SocketTimeoutException) {//网络链接超时
            //   Log.d(TAG, "1------------ 网络链接超时");
            baseResponse.setError(Error.ERROR_NET_TIMEOUT);
            EventBus.getDefault().post(baseResponse);
        } else {//未知错误
            if (NetworkUtil.isNetWorkAvailable(context)) {
                baseResponse.setError("error_inner_error");
                EventBus.getDefault().post(baseResponse);
                e.printStackTrace();//对于未知错误进行打印,大部分为程序逻辑错误
            } else {
                //     Log.d(TAG, "1------------ 无网络");
                baseResponse.setError(Error.ERROR_NETWORK_IS_NOT_AVAILABLE);
                EventBus.getDefault().post(baseResponse);
            }
        }
    }

}

